#include <iostream>

#include <QtGui>

#include "invader_font.h"
#include "media.h"

static const char * const xpm_unknown[] = {
  "10 10 2 1",
  ". c #000000",
  "x c #ffffff",
  "xx..xx..xx",
  "xx..xx..xx",
  "..xx..xx..",
  "..xx..xx..",
  "xx..xx..xx",
  "xx..xx..xx",
  "..xx..xx..",
  "..xx..xx..",
  "xx..xx..xx",
  "xx..xx..xx"
};

const InvaderFont & InvaderFont::instance ()
{
  if (_instance == 0)
    _instance = new InvaderFont (MEDIA_DIR INVADER_FONT_DIR);

  return *_instance;
}

void InvaderFont::destroy ()
{
  if (_instance != 0)
    delete _instance;
}

const QPixmap & InvaderFont::operator[] (const QChar &c) const
{
  std::map<char, QPixmap>::const_iterator pix = _glyphs.find (
    c.toLower ().toAscii ());

  if (pix == _glyphs.end ())
    return _unknownGlyph;

  return pix->second;
}

InvaderFont::InvaderFont (const QString &dir)
  : _unknownGlyph (QPixmap (xpm_unknown))
{
  QStringList filter;
  filter << "*.bmp";

  /* QDir::Hidden needed needed to read ..bmp file */
  QDirIterator di (dir, filter, QDir::Files | QDir::Hidden);

  for (; di.hasNext ();) {
    di.next ();
    QString tmp = di.fileName ();

    _glyphs[tmp.begin ()->toLower ().toAscii ()] = QPixmap (di.filePath ());
  }
}

InvaderFont * InvaderFont::_instance = 0;
